#pragma once
#include <set>
#include <string>
#include <cstring>
#include "Log.hpp"
#include "InetAddr.hpp"
class command
{
public:
    command()
    {
        commandlist.insert("rm");
        commandlist.insert("ls");
        commandlist.insert("touch");
        commandlist.insert("pwd");
    }
    ~command() {}
    bool SafeCheck(std::string cmd)
    {
        for (auto &e : commandlist)
        {
            if (strncmp(e.c_str(), cmd.c_str(), e.size()) == 0)
            {
                return true;
            }
        }
        return false;
    }
    std::string Execute(std::string commandstr)
    {
        if (!SafeCheck(commandstr))
        {
            return "unsafe";
        }
        std::string result;
        FILE *in = popen(commandstr.c_str(), "r");
        if (in)
        {
            char line[1024];
            while (fgets(line, sizeof(line), in))
            {
                result += line;
            }
            return result.empty() ? "success" : result;
        }
        return "Excute err";
    }

    void Hander(int sockfd, InetAddr addr)
    {
        while (true)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(DEBUG, "[%s]#%s\n", addr.AddrStr().c_str(), buffer);
                std::string result=Execute(buffer);
                n = write(sockfd, result.c_str(), sizeof(result));
                if (n < 0)
                {
                    LOG(ERROR, "server write false!\n");
                }
            }
            else if (n == 0) // 读到文件结尾
            {
                LOG(INFO, "%s quit!\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(INFO, "read error!\n");
                break;
            }
        }
        ::close(sockfd);
    }
private:
    std::set<std::string> commandlist;
};